using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 独立的项目清理控制台应用程序
    /// </summary>
    public class CleanupConsole
    {
        public static async Task<int> Main(string[] args)
        {
            Console.WriteLine("=== 项目清理工具 ===");
            Console.WriteLine();

            try
            {
                // 获取项目路径
                string projectPath;
                if (args.Length > 0)
                {
                    projectPath = args[0];
                }
                else
                {
                    Console.Write("请输入项目路径（默认为 '诡异收藏家'）: ");
                    var input = Console.ReadLine();
                    projectPath = string.IsNullOrWhiteSpace(input) ? "诡异收藏家" : input;
                }

                // 转换为绝对路径
                if (!Path.IsPathRooted(projectPath))
                {
                    projectPath = Path.Combine(Environment.CurrentDirectory, projectPath);
                }

                Console.WriteLine($"项目路径: {projectPath}");

                if (!Directory.Exists(projectPath))
                {
                    Console.WriteLine($"错误: 项目路径不存在: {projectPath}");
                    return 1;
                }

                // 创建服务容器
                var services = new ServiceCollection();
                ConfigureServices(services);
                var serviceProvider = services.BuildServiceProvider();

                var cleanupService = serviceProvider.GetRequiredService<ProjectCleanupService>();

                Console.WriteLine();
                Console.WriteLine("开始项目清理...");
                Console.WriteLine("这将包括以下操作:");
                Console.WriteLine("1. 清理重复文件");
                Console.WriteLine("2. 统一文件命名规范");
                Console.WriteLine("3. 清理文件内容（移除错误信息和占位符）");
                Console.WriteLine("4. 移除空文件和无效文件");
                Console.WriteLine();

                Console.Write("是否继续？(y/N): ");
                var confirm = Console.ReadLine();

                if (confirm?.ToLower() != "y" && confirm?.ToLower() != "yes")
                {
                    Console.WriteLine("操作已取消");
                    return 0;
                }

                Console.WriteLine();
                Console.WriteLine("开始清理项目...");

                // 执行清理
                var cleanupResult = await cleanupService.CleanupProjectAsync(projectPath);

                Console.WriteLine();
                Console.WriteLine("=== 清理结果 ===");
                Console.WriteLine($"总处理文件数: {cleanupResult.TotalProcessed}");
                Console.WriteLine($"清理文件数: {cleanupResult.CleanedFiles.Count}");
                Console.WriteLine($"重命名文件数: {cleanupResult.RenamedFiles.Count}");
                Console.WriteLine($"移除文件数: {cleanupResult.RemovedFiles.Count}");

                if (cleanupResult.CleanedFiles.Count > 0)
                {
                    Console.WriteLine();
                    Console.WriteLine("清理的文件:");
                    foreach (var file in cleanupResult.CleanedFiles)
                    {
                        Console.WriteLine($"  ✓ {file}");
                    }
                }

                if (cleanupResult.RenamedFiles.Count > 0)
                {
                    Console.WriteLine();
                    Console.WriteLine("重命名的文件:");
                    foreach (var rename in cleanupResult.RenamedFiles)
                    {
                        Console.WriteLine($"  ↻ {rename}");
                    }
                }

                if (cleanupResult.RemovedFiles.Count > 0)
                {
                    Console.WriteLine();
                    Console.WriteLine("移除的文件:");
                    foreach (var file in cleanupResult.RemovedFiles)
                    {
                        Console.WriteLine($"  ✗ {file}");
                    }
                }

                Console.WriteLine();
                Console.WriteLine(cleanupResult.IsSuccess ? "✓ 清理完成" : "⚠ 清理过程中遇到问题");
                Console.WriteLine(cleanupResult.Message);

                return cleanupResult.IsSuccess ? 0 : 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
                Console.WriteLine($"详细信息: {ex}");
                return 1;
            }
            finally
            {
                Console.WriteLine();
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            // 注册基础服务
            services.AddSingleton<IDataStorageService, JsonDataStorageService>();
            services.AddSingleton<IThinkingChainService, ThinkingChainService>();

            // 注册清理相关服务
            services.AddScoped<ContentQualityService>();
            services.AddScoped<ProjectCleanupService>();

            // 配置日志
            services.AddLogging(builder =>
            {
                builder.AddConsole();
                builder.SetMinimumLevel(LogLevel.Information);
            });
        }
    }
}

/// <summary>
/// 编译和运行说明：
/// 
/// 1. 编译：
///    csc CleanupConsole.cs -reference:Microsoft.Extensions.DependencyInjection.dll -reference:Microsoft.Extensions.Logging.dll
/// 
/// 2. 或者使用dotnet：
///    dotnet run CleanupConsole.cs
/// 
/// 3. 功能说明：
///    - 清理重复文件：识别并移除同一章节的重复文件，保留最新版本
///    - 统一文件命名：将文件名标准化为统一格式
///    - 清理文件内容：移除AI思维链、错误信息、占位符等无效内容
///    - 移除无效文件：删除空文件或内容过少的文件
/// 
/// 4. 安全措施：
///    - 所有被移除或修改的文件都会自动备份
///    - 备份文件保存在项目的"备份"目录中
///    - 支持操作前确认，避免误操作
/// </summary>
